<template>
  <div class="m-5 space-y-5">

    <div class="flex justify-between">
      <div>
        <n-dropdown trigger="hover" :options="typeOptions" @select="handleTypeSelect">
          <n-button type="info" size="large">{{ type ? type : '全部' }}</n-button>
        </n-dropdown>
      </div>
      <div class="flex space-x-3">
        <n-button @click="handleAdd" type="primary" size="large">添加键值</n-button>
        <n-input :loading="loading" v-model:value="keyword" size="large" placeholder="请输入关键字" @keydown.enter="getData"
                 round>
          <template #prefix>
            <n-icon size="28">
              <icon icon="mdi:search" ></icon>
            </n-icon>
          </template>
        </n-input>
      </div>
    </div>
    <n-data-table :data="dataList"
                  :remote="true"
                  :columns="columns"
                  :loading="loading"
                  :min-height="300"
                  :pagination="pagination">
    </n-data-table>
  </div>
  <CreateKeyModal ref="createKeyModalRef" @onSubmit="handleSubmit"></CreateKeyModal>
</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
import {h, onMounted, ref, watch} from "vue";
import {NButton, NText} from "naive-ui";
import dayjs from "@/utils/time";
import {useClipboard} from "@vueuse/core";
import api from "@/api";
import {useDatabaseStore} from "@/store";
import router from "@/router";
import CreateKeyModal from "@/components/modal/CreateKeyModal.vue";
import {Icon} from "@iconify/vue";

const databaseStore = useDatabaseStore()
const {copy} = useClipboard()
const route = useRoute()
const key = ref(route.params.key)
const index = ref(route.params.index)
const createKeyModalRef = ref()
const keyword = ref('')
const type = ref('')

onMounted(() => [
  getData()
])
watch(route, () => {
  key.value = route.params.key
  index.value = route.params.index
  pagination.value.pageNo = 1
  getData()
})


const dataList = ref()
const loading = ref(false)
const pagination = ref({
  pageNo: 1,
  pageSize: 15,
  showSizePicker: true,
  pageSizes: [5, 8, 15],
  itemCount: 0,
  onChange: (page: number) => {
    pagination.value.pageNo = page
    getData()
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.value.pageNo = 1
    pagination.value.pageSize = pageSize
    getData()
  }
})
const columns = ref([
  {
    width: 1,
    type: 'expand',
    renderExpand: (row: any) => {
      return h('pre', {
        class: 'break-all'
      }, {default: () => JSON.stringify(row.data, null, 2)})
    }
  },
  {
    title: '#',
    width: 2,
    key: 't',
    render: (_: any, index: any) => {
      return `${index + 1}`
    }
  },
  {title: 'key', key: 'key', width: 3, ellipsis: {tooltip: true}, align: 'center',},
  {title: '类型', key: 'type', width: 2, ellipsis: {tooltip: true}, align: 'center',},
  {
    title: '数据', key: 'data', width: 7, ellipsis: {tooltip: true}, align: 'center',
    render(row: any) {
      return h(NText, {
        class: 'cursor-pointer',
        onClick: () => handleCopy(JSON.stringify(row.data))
      }, {default: () => JSON.stringify(row.data)})
    }
  },
  {
    title: '元素数', key: 'dataNum', width: 2, ellipsis: {tooltip: true}, align: 'center',
    render(row: any) {
      return h(NText, {}, {default: () => typeof (row.data) === 'string' ? '1' : Object.keys(row.data).length || '-'})
    }
  },
  {
    title: '过期时间', key: 'expire', width: 4, ellipsis: {tooltip: true}, align: 'center',
    render(row: any) {
      return row.expire === -1 ? '无期限' : dayjs.unix(row.expire).fromNow(true) || '-'
    }
  },
  {
    title: '操作', key: 'actions', width: 6, align: 'center',
    render(row: any) {
      return [
        h(NButton, {
          round: true,
          secondary: true,
          size: 'small',
          type: "warning",
          onClick: () => handleEdit(row)
        }, {default: () => "编辑"}),
        h(NButton, {
          round: true,
          secondary: true,
          size: 'small',
          type: "error",
          onClick: () => handleRemoveKey(row)
        }, {default: () => "删除"}),
      ]
    }
  }
])
const typeOptions = ref([
  {
    label: '全部',
    key: '',
  },
  {
    label: 'string',
    key: 'string',
  },
  {
    label: 'list',
    key: 'list',
  },
  {
    label: 'set',
    key: 'set',
  },
  {
    label: 'zset',
    key: 'zset',
  },
  {
    label: 'hash',
    key: 'hash',
  },
])
const handleTypeSelect = (val: any) => {
  type.value = val
  if (val === '') {
    type.value = ''
  }
  getData()
}

const handleCopy = (row: any) => {
  copy(row)
  window.$message.success("复制成功")
}


const handleAdd = () => {
  createKeyModalRef.value.doShow()
}

const handleEdit = (row: any) => {
  createKeyModalRef.value.doParamsShow(row)
}
const handleRemoveKey = (row: any) => {
  window.$dialog.warning({
    title: '确定要删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      api.redis.removeKey({
        name: key.value,
        index: index.value,
        key: row.key
      }).then((res: any) => {
        if (res.data.code === 0) {
          window.$message.success(res.data.msg)
          getData()
        } else {
          databaseStore.errorDb(key.value)
        }
      })
    }
  })
}


const getData = () => {
  loading.value = true
  if (key.value && index.value) {
    api.redis.query({
      name: key.value,
      index: index.value,
      pageNo: pagination.value.pageNo,
      pageSize: pagination.value.pageSize,
      keyword: keyword.value,
      type: type.value
    }).then((res: any) => {
      if (res.data.code === 0) {
        pagination.value.itemCount = res.data.data.totalKeyNum
        dataList.value = res.data.data.list
        databaseStore.successDb(key.value)
      } else {
        databaseStore.errorDb(key.value)
        router.push({
          path: '/info/' + encodeURIComponent(key.value.toString()) + '/',
        })
      }
    }).finally(() => {
      loading.value = false
    })
  }
}

const handleSubmit = () => {
  getData()
}
</script>

<style scoped>

</style>